package leetcode_interview;

public class I0106 {

    public static void main(String[] args) {
        I0106 i0106 = new I0106();
        i0106.compressString("aabcccccaa");
    }

    public String compressString1(String S) {
        StringBuffer sb = new StringBuffer();
        int length = S.length(), i = 0;
        while (i < length) {
            char c = S.charAt(i);
            sb.append(c);
            int count = 0;
            while (i < length && c == S.charAt(i)) {
                count++;
                i++;
            }
            sb.append(count);
        }
        return sb.length() < S.length() ? sb.toString() : S;
    }

    public String compressString(String S) {
        if (S == null || S.length() == 0)
            return S;
        StringBuffer sb = new StringBuffer();
        int length = S.length();
        char lastChar = S.charAt(0);
        int count = 0;
        for (int i = 0; i < length; i++) {
            char c = S.charAt(i);
            if (c == lastChar)
                count++;
            else {
                sb.append(lastChar).append(count);
                lastChar = c;
                count = 1;
            }
        }
        sb.append(lastChar).append(count);
        System.out.println(sb);
        return sb.length() < S.length() ? sb.toString() : S;
    }

}
